package com.wkbb.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FileUtil {

    public void downloadNet(String wjurl, HttpServletRequest req, HttpServletResponse response) {
        Map<String, String> urlByLoanid = new HashMap<String, String>();
        try {
            if (urlByLoanid != null) {
                int i = wjurl.lastIndexOf("/");
                String fileName = wjurl.substring(i + 1);

                URL url = new URL(wjurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置超时间为3秒
                conn.setConnectTimeout(3 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                //得到输入流
                InputStream inputStream = conn.getInputStream();
                //获取自己数组
                byte[] bs = readInputStream(inputStream);
                response.setContentType("application/octet-stream;charset=ISO8859-1");
                BufferedOutputStream output = null;
                BufferedInputStream input = null;
                try {
                    output = new BufferedOutputStream(response.getOutputStream());
                    // 中文文件名必须转码为 ISO8859-1,否则为乱码
                    String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
                    // 作为附件下载
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);

                    output.write(bs);
                    response.flushBuffer();
                } catch (Exception e) {
                    log.error("Download log file error", e);
                } finally {
                    if (input != null) {
                        input.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * 　　* 网络图片转换Base64的方法
     * 　　* @param netImagePath
     */
    private static String netImageToBase64(String netImageUrl) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(netImageUrl);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(data.toByteArray());
        return Base64.getEncoder().encodeToString(data.toByteArray());
    }

    /**
     * @param imgStr base64编码字符串
     * @param path   图片路径-具体到文件
     * @return
     * @Description: 将base64编码字符串转换为图片
     * @Author:
     * @CreateTime:
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null) {
            return false;
        }
        try {
            // 解密
//        BASE64Decoder decoder = new BASE64Decoder();
//            byte[] b = decoder.decodeBuffer(imgStr);
            byte[] b = Base64.getDecoder().decode(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }

        return toFile;
    }

    /**
     * File 转 MultipartFile
     *
     * @param file
     * @throws Exception
     */
    public static void fileToMultipartFile(File file) throws Exception {

        FileInputStream fileInput = new FileInputStream(file);
        MultipartFile toMultipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(fileInput));
        toMultipartFile.getInputStream();

    }


    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 输出文件到客户端
     * @param file 文件
     * @param fileName 文件名称
     * @param response 响应对象
     */
    public static void downloadFile(File file,String fileName,HttpServletResponse response) {
        InputStream fis = null;
        OutputStream toClient = null;
        FileInputStream fileInputStream=null;
        try {
            fileInputStream=new FileInputStream(file);
            fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 清空response
            response.reset();

            // 设置response的Header
//            response.setHeader("Content-Disposition","attachment;filename=" +
//                    URLEncoder.encode(fileName+file.getName().substring(file.getName().lastIndexOf(".")),"UTF-8"));
            String suffix = file.getName().substring(file.getName().lastIndexOf("."));
            response.addHeader("Content-Disposition", "attachment; filename=\"" +
                    new String((fileName+suffix).getBytes("UTF-8"), "ISO-8859-1") + "\";filename*=UTF-8''"+
                    new String((fileName+suffix).getBytes("UTF-8"), "ISO-8859-1"));

            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());

            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
//            response.setContentType("multipart/form-data;charset=utf-8");
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setContentType("application/octet-stream");

            toClient.write(buffer);
            toClient.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(file!=null){file.delete();}
                if(fis!=null)fis.close();
                if(toClient!=null)toClient.close();
                if(fileInputStream!=null)fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 图片转化成base64字符串
     * @return
     */
    private String getImageStr(MultipartFile file)
    {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try
        {
            in = file.getInputStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(data);//返回Base64编码过的字节数组字符串
        return Base64.getEncoder().encodeToString(data);//返回Base64编码过的字节数组字符串
    }

    public static void main(String args[]) {

        String imgStr = FileUtil.netImageToBase64("https://t12.baidu.com/it/u=1123336169,2893259886&fm=76");
        log.info(imgStr);

        FileUtil.generateImage(imgStr, "D:\\test.jpg");

    }
}
